<template>
  <div class="tags-navigation-container">
    <!-- 左侧导航栏 -->
    <div class="tags-sidebar">
      <div class="sidebar-header">
        <h3>热门标签</h3>
        <el-input
          v-model="searchQuery"
          placeholder="搜索标签..."
          size="small"
          clearable
          class="search-input"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <div class="tags-list">
        <div
          v-for="tag in filteredTags"
          :key="tag.tagId"
          class="tag-item"
          :class="{ active: activeTag?.tagId === tag.tagId }"
          @click="selectTag(tag)"
        >
          <span class="tag-name">{{ tag.tagName }}</span>
          <span class="tag-count">{{ tag.usageCount }}</span>
        </div>

        <div v-if="filteredTags.length === 0" class="empty-tips">
          <el-empty description="没有找到相关标签" :image-size="80" />
        </div>
      </div>
    </div>

    <!-- 右侧详情区域 -->
    <div class="tag-detail">
      <div v-if="!activeTag" class="welcome-message">
        <h2>欢迎来到标签中心</h2>
        <p>请从左侧选择一个标签查看相关内容</p>
        <el-icon class="welcome-icon"><Pointer /></el-icon>
      </div>

      <div v-else class="tag-content">
        <div class="tag-header">
          <h2>{{ activeTag.tagName }}</h2>
          <!-- <el-tag :type="getTagType(activeTag)" effect="dark" round>
            使用次数: {{ activeTag.usageCount }}
          </el-tag> -->
        </div>

        <el-divider />

        <!-- 加载状态 -->
        <div v-if="contentLoading" class="loading-container">
          <el-icon class="loading-icon"><Loading /></el-icon>
          <span>加载中...</span>
        </div>

        <!-- 错误提示 -->
        <el-alert
          v-else-if="contentError"
          type="error"
          :title="contentError"
          show-icon
          closable
          class="error-alert"
        />

        <!-- 内容列表 -->
        <div v-else class="content-list">
          <div v-if="contents.length === 0" class="empty-content">
            <el-empty description="暂无相关内容" />
          </div>

          <div v-else>
            <div class="content-item" v-for="content in contents" :key="content.contentId">
              <h3 class="content-title">{{ content.title }}</h3>
              <p class="content-summary">{{ content.summary }}</p>
              <div class="content-meta">
                <span class="meta-item">
                  <el-icon><User /></el-icon>
                  {{ content.username || '匿名用户' }}
                </span>
                <span class="meta-item">
                  <el-icon><Clock /></el-icon>
                  {{ formatDate(content.publishTime) }}
                </span>
                <span class="meta-item">
                  <el-icon><View /></el-icon>
                  {{ content.readCount || 0 }} 阅读
                </span>
              </div>
              <el-button
                type="primary"
                size="small"
                @click="viewContentDetail(content)"
                class="view-detail-btn"
              >
                查看详情
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
import { watch } from 'vue'
import {
  Search,
  Pointer,
  Loading,
  User,
  Clock,
  View
} from '@element-plus/icons-vue'

const allTags = ref([])
const loading = ref(false)
const error = ref(null)
const searchQuery = ref('')
const activeTag = ref(null)
const contents = ref([])
const contentLoading = ref(false)
const contentError = ref(null)
const router = useRouter()

// 计算属性：过滤后的标签列表
const filteredTags = computed(() => {
  if (searchQuery.value) {
    return allTags.value.filter(tag =>
      tag.tagName.toLowerCase().includes(searchQuery.value.toLowerCase())
    )
  }
  return allTags.value
})

// 获取标签类型样式
const getTagType = (tag) => {
  if (tag.isHot) return 'danger'
  if (tag.usageCount > 100) return 'warning'
  if (tag.usageCount > 50) return 'success'
  return 'primary'
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知时间'
  const date = new Date(dateString)
  return date.toLocaleDateString()
}

// 查看内容详情
const viewContentDetail = (content) => {
  console.log('查看内容详情:', content.contentId)
  // 这里可以添加跳转到内容详情页的逻辑
 router.push(`/content/${content.contentId}`)
}

// 选择标签并获取相关内容
const selectTag = async (tag) => {
  activeTag.value = tag
  contentLoading.value = true
  contentError.value = null

  // 更新路由参数
  router.push({ name: 'Hot', params: { tagId: tag.tagId } })

  try {
    const response = await axios.get(`http://127.0.0.1:8081/app/tags/${tag.tagId}`)
    contents.value = response.data.data || []
  } catch (err) {
    contentError.value = err.response?.data?.message || '获取内容失败'
    contents.value = []
  } finally {
    contentLoading.value = false
  }
}
// 获取标签数据
const fetchTags = async () => {
  try {
    loading.value = true
    const response = await axios.get('http://127.0.0.1:8081/app/tags/all')
    allTags.value = response.data.data
      .filter(tag => tag.tagName)
      .sort((a, b) => (b.usageCount || 0) - (a.usageCount || 0))

    // 检查路由参数
    const routeTagId = router.currentRoute.value.params.tagId
    if (routeTagId) {
      const tag = allTags.value.find(t => t.tagId == routeTagId)
      if (tag) {
        selectTag(tag)
        return
      }
    }

    // 默认选择第一个标签
    if (allTags.value.length > 0) {
      selectTag(allTags.value[0])
    }
  } catch (err) {
    error.value = err.response?.data?.message || '获取标签数据失败'
  } finally {
    loading.value = false
  }
}
watch(
  () => router.currentRoute.value.params.tagId,
  (newTagId) => {
    if (newTagId) {
      const tag = allTags.value.find(t => t.tagId == newTagId)
      if (tag) {
        selectTag(tag)
      }
    }
  },
  { immediate: true }
)

onMounted(() => {
  fetchTags()
})
</script>

<style scoped lang="scss">
.tags-navigation-container {
  display: flex;
  height: calc(100vh - 60px);
  background-color: #f5f7fa;

  .tags-sidebar {
    width: 280px;
    background-color: #fff;
    border-right: 1px solid #e6e6e6;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .sidebar-header {
      width: 300px;
      padding: 15px;
      border-bottom: 1px solid #e6e6e6;

      h3 {
        margin: 0 0 12px 0;
        font-size: 18px;
        color: #333;
      }

      .search-input {
        :deep(.el-input__inner) {
          border-radius: 16px;
        }
      }
    }

    .tags-list {
      flex: 1;
      overflow-y: auto;
      padding: 8px 0;

      .tag-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 10px 20px;
        cursor: pointer;
        transition: all 0.2s;
        border-left: 3px solid transparent;

        &:hover {
          background-color: #f0f7ff;
          border-left-color: var(--el-color-primary);
        }

        &.active {
          background-color: #e6f1ff;
          border-left-color: var(--el-color-primary);
          font-weight: 500;
        }

        .tag-name {
          flex: 1;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .tag-count {
          background-color: #f0f0f0;
          border-radius: 10px;
          padding: 2px 8px;
          font-size: 12px;
          color: #666;
        }
      }

      .empty-tips {
        padding: 40px 20px;
        text-align: center;
        color: #999;
      }
    }
  }

  .tag-detail {
    flex: 1;
  }
  </style>
